import requests
import datetime
import pandas as pd


class WeatherUtils(object):
    def __init__(self):
        self.date = [
            '2024-07-01',
            '2024-08-01',
            '2024-09-01',
            '2024-10-01',
            '2024-11-01',
            '2024-12-01',
        ]
        self.url = 'http://v1.yiketianqi.com/api'

    def get_data(self):
        """获取天气数据"""
        data_list = []
        for d in self.date:
            conf = {
                "appid": "48766619",  # 替换成自己的appid
                "appsecret": "V9Gx9Cul",  # 替换成自己的appsecret
                "date": d[:4],
                "month": d[5:7],
                "city": "南昌",  # 添加日期参数
            }
            try:
                res = requests.get(self.url + '?', params=conf)
                res.raise_for_status()  # 检查请求是否成功
                res_data = res.json()

                # 打印API返回的数据，以便调试
                print("API返回的数据:", res_data)

                # 根据实际返回的数据结构调整字段名
                for i in res_data.get('data', []):  # 使用get方法避免KeyError
                    ymd = i.get('ymd', '')
                    if ymd:  # 确保ymd字段存在且不为空
                        try:
                            date_obj = datetime.datetime.strptime(ymd, '%Y-%m-%d')
                            data_list.append({
                                'date': date_obj,
                                'bWendu': i.get('bWendu', ''),
                                'yWendu': i.get('yWendu', ''),
                                'tianqi': i.get('tianqi', ''),
                                'fengli': i.get('fengli', ''),
                            })
                        except ValueError:
                            print(f"无法解析日期: {ymd}")
            except requests.RequestException as e:
                print(f"请求日期 {d} 的天气数据时出错: {e}")

        df = pd.DataFrame(data_list)
        df.to_csv('./timing/weather.csv', index=False)  # 保存CSV文件时不保存索引
        print("天气数据已成功保存到 ./timing/weather.csv")


if __name__ == '__main__':
    wu = WeatherUtils()
    wu.get_data()